package com.shf.service.impl;

import com.shf.entity.Role;
import com.shf.entity.Users;
import com.shf.mapper.UserMapper;
import com.shf.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service("loginuser")
public class UsersServiceImpl implements UsersService {

    @Autowired
    UserMapper userMapper;
    /**
     * 根据用户名对比 数据库用户
     * @param
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名对比 数据库用户
        Users loginUser = userMapper.findUser(username);


        //创建一个认证对象
        User user = new User(loginUser.getUsername(),"{noop}"+loginUser.getPassword(),loginUser.getStatus()==0?false:true,true,true,true,getRoles(loginUser.getRoles()));

        return user;


    }

    /**
     * 提取用户的角色权限名称
     * @param roles
     * @return
     */
    private Collection<? extends GrantedAuthority> getRoles(List<Role> roles) {

        List<SimpleGrantedAuthority> list = new ArrayList<SimpleGrantedAuthority>();
        for (Role role : roles) {

            System.out.println(role.getRoleName());

            SimpleGrantedAuthority sa = new SimpleGrantedAuthority("ROLE_"+role.getRoleName());

            list.add(sa);
        }



        return list;
    }
}
